﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using Shared;
using System.Diagnostics;
using System.Threading;
using System.Configuration;
using System.IO;
using System.Runtime.Serialization;
using RastinArgham.Robots.Activator.RobotWCF;

namespace RastinArgham.Robots.Activator
{
    class Program
    {
        private static List<Activate> ActivationData = new List<Activate>();

        static void Main(string[] args)
        {
            Host();

            while (true)
            {
                Console.WriteLine("Robot is awake and is going to start his job!");
                KillJobs();
                GetActivationData();

                Console.WriteLine("Robot has " + ActivationData.Count + " task(s) to perform!");
                foreach (var item in ActivationData)
                {
                    Console.WriteLine("Executing OrderID " + item.OrderId);
                    Execute(item);

                    while (Process.GetProcessesByName("Activation").Length != 0)
                    {
                        Thread.Sleep(30 * 1000);
                    }
                }

                Console.WriteLine("Robot is going to sleep for 2 minutes!");
                Thread.Sleep(2 * 60 * 1000);
            }
        }

        private static void GetActivationData()
        {
            ActivationData.Clear();

            CRMRobotWCFClient robotService = new CRMRobotWCFClient();
            ActivationInfo[] activationInfo = robotService.GetActivationUsernames();

            foreach (var item in activationInfo)
            {
                if (String.IsNullOrEmpty(item.Username))
                    robotService.UsernameActivationReport(item.OrderId, "", false, "کاربر فاقد شناسه کاربری می باشد");
                else
                    ActivationData.Add(new Activate { Identity = item.Username, OrderId = item.OrderId, OrderStateId = item.OrderStateId });
            }
        }

        private static void Execute(Activate data)
        {
            try
            {
                data.TimeStamp = DateTime.Now;

                string parameter = String.Empty;

                DataContractSerializer ds = new DataContractSerializer(typeof(Activate));

                using (MemoryStream m = new MemoryStream())
                {
                    ds.WriteObject(m, data);

                    byte[] buffer = m.ToArray();

                    parameter =
                        Convert.ToBase64String(buffer) + " " +
                        (bool.Parse(ConfigurationSettings.AppSettings["debug"].ToString()) ? "debug" : "nodebug") + " " +
                        ConfigurationSettings.AppSettings["timeout"].ToString() + " " +
                        ConfigurationSettings.AppSettings["url"].ToString() + " " +
                        ConfigurationSettings.AppSettings["interval"].ToString() + " " +
                        ConfigurationSettings.AppSettings["username"].ToString() + " " +
                        ConfigurationSettings.AppSettings["password"].ToString() + " " +
                        ConfigurationSettings.AppSettings["special-username"].ToString() + " " +
                        ConfigurationSettings.AppSettings["special-password"].ToString();

                    string s = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\RastinArgham.Robots.Activation.exe";

                    Process.Start(s, parameter);

                }
            }
            catch (Exception ex)
            {
#if debug
                MessageBox.Show(ex.Message);
#endif
                Console.WriteLine(ex.Message);
                //SetState(false);
            }

        }

        private static void KillJobs()
        {
            foreach (var item in Process.GetProcessesByName("Activation"))
            {
                item.Kill();
            }
        }

        private static void Host()
        {
            ServiceHost syncHost =
                new ServiceHost(
                    typeof(ReportService),
                    new Uri[] { new Uri("net.pipe://localhost/Activation") });

            syncHost.AddServiceEndpoint(
                typeof(IReportService),
                new NetNamedPipeBinding(),
                "ReportService");

            syncHost.Open();
        }

    }
}
